package com.njust.controller;


import com.njust.dao.DepartmentDao;
import com.njust.dao.EmployeeDao;
import com.njust.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class Employee2Controller {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;


    @RequestMapping(value = "/emp2Add", method = RequestMethod.POST)
    public String addEmp(@Valid Employee employee, BindingResult bindingResult, Model model){
        System.out.println("Employee2Controller");
        System.out.println("要添加的员工：" + employee);
        System.out.println(employee.hashCode());
        // 获取是否有校验错误
        boolean hasErrors = bindingResult.hasErrors();
        Map<String, Object> errorsMap = new HashMap<>();
        if (!hasErrors){
            employeeDao.save(employee);
        }else {
            System.err.println("绑定出错！！！");
            List<FieldError> errors = bindingResult.getFieldErrors();
            for (FieldError fieldError : errors) {

                System.out.println("错误消息提示：" + fieldError.getDefaultMessage());
                System.out.println("错误的字段是？" + fieldError.getField());
                System.out.println(fieldError);
                System.out.println("------------------------");
                errorsMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            model.addAttribute("errorInfo", errorsMap);

            return "add.jsp";
        }
        return "redirect:/emps";
    }

//    @ModelAttribute
//    public void modelAttribute(HttpServletRequest request, HttpServletResponse response, Model model){
//        String lastName = request.getParameter("lastName");
//        String email = request.getParameter("email");
//        Integer gender = Integer.parseInt(request.getParameter("gender"));
//
//    }
}
